const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    domain: app.api.domain,
    currentData: 0,
    windowWidth: '',
    tickets: [],
    noData: true,
    status: [
      {
        pagination: 1,
        isEnd: false,
        isEmpty: false
      },
      {
        pagination: 1,
        isEnd: false,
        isEmpty: false
      },
      {
        pagination: 1,
        isEnd: false,
        isEmpty: false
      }
    ],
    selectstoreid : '',
    shareImg: '',
  },


  computed(value) {
    const that = this;
    return value / 750 * that.data.windowWidth;
  },

  drawProgressbg(id) {
    const that = this;
    // 使用 wx.createContext 获取绘图上下文 context
    let ctx = wx.createCanvasContext(id)
    ctx.setLineWidth(that.computed(10)); // 设置圆环的宽度
    ctx.setStrokeStyle('#901404'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath(); //开始一个新的路径
    ctx.arc(that.computed(75), that.computed(75), that.computed(53), -4 / 3 * Math.PI, 1 / 3 * Math.PI, false);
    ctx.stroke(); //对当前路径进行描边
    ctx.draw();
  },

  drawCircle(id, data) {
    const that = this;
    let ctx = wx.createCanvasContext(id);
    ctx.setLineWidth(that.computed(10)); // 设置圆环的宽度
    ctx.setStrokeStyle('#fff'); // 设置圆环的颜色
    ctx.setLineCap('round') // 设置圆环端点的形状
    ctx.beginPath();
    ctx.arc(that.computed(75), that.computed(75), that.computed(53), -4 / 3 * Math.PI, (-4 / 3 + data.percent / 100 * 5 / 3) * Math.PI, false);
    ctx.stroke();
    ctx.draw()
  },
  draw(data) {
    const that = this;
    console.log(data)
    for (let i = 0; i < data.length; i++) {
      data[i].processText = data[i].createnum == 0 ? '不限量' : data[i].send_num == data[i].createnum ? "已抢光" : "已抢";
      data[i].percent = parseInt(data[i].send_num / data[i].createnum * 100);
        that.setData({
          tickets: that.data.tickets
        })

      // 开始绘制
      if (data[i].createnum == 0) {
        data[i].percent = 0;
      }
      that.drawProgressbg("bg" + i); // 绘制背景
      that.drawCircle("process" + i, data[i]); // 绘制进度

    }
  },

  // 获取数据
  getData(type) {
    const that = this;
    let token = app.globalData.token;
    let index = type - 1;
    let status = that.data.status;
    let json = {
      token,
      type: type,
      select_store_id: that.data.selectstoreid ? that.data.selectstoreid : app.globalData.address.select_store_id,
      p: status[index].pagination,
      crd_store_id: app.globalData.nextdayStore?app.globalData.nextdayStore:'0'
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.toGoo, jsonData).then(res => {
      console.log(res)
      if (res.status == 1) {
        res.result.coupon_list.forEach(item => {
          item.use_start_time = app.moment(item.use_start_time * 1000).format('YYYY.MM.DD');
          item.use_end_time = app.moment(item.use_end_time * 1000).format('YYYY.MM.DD');
          item.money = item.money.split('.');
          item.condition = item.condition.split('.');
          item.percent = 0;
          item.processText = "已抢";
          if (item.isget == 1) {
            item.btnText = '已领取';
            item.color = '#999'
          } else if (item.isget == 0) {
            item.btnText = '点击领取';
          }
        })
        that.setData({
          [`tickets[${index}]`]: res.result.coupon_list
        }, () => {
          that.setData({
            hiddenLoading: true
          })
          setTimeout(() => {
            that.draw(that.data.tickets[that.data.currentData])
          }, 300)
        })
        if (that.data.tickets[index] == '') {
          that.setData({
            [`status[${index}].isEmpty`]: true
          })
        }
      } else {
        throw res.msg;
      }
    }).catch(err => {
      that.setData({
        hiddenLoading: true
      })
      app.showInfo(err.toString())
    })
  },

  // 获取数据
  getMoreData() {
    const that = this;
    let index = that.data.currentData;
    if (that.data.status[index].isEnd) {
      return
    }
    let token = app.globalData.token;
    let json = {
      token,
      type: parseInt(index) + 1,
      select_store_id: that.data.selectstoreid ? that.data.selectstoreid : app.globalData.address.select_store_id,
      p: that.data.status[index].pagination + 1,
      crd_store_id:  app.globalData.nextdayStore?app.globalData.nextdayStore:'0'
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.toGoo, jsonData).then(res => {
      if (res.status == 1) {
        // 分页判断
        let len = res.result.coupon_list;
        if (len == 0) {
          that.setData({
            [`status[${index}].isEnd`]: true,
            hiddenLoading: true
          })
          wx.showToast({
            title: '没有更多了',
            icon: 'none',
            duration: 1000
          })
        } else {
          res.result.coupon_list.forEach(item => {
            item.use_start_time = app.moment(item.use_start_time * 1000).format('YYYY.MM.DD');
            item.use_end_time = app.moment(item.use_end_time * 1000).format('YYYY.MM.DD');
            item.money = item.money.split('.');
            item.condition = item.condition.split('.');
            item.percent = 0;
            item.processText = "已抢";
            if (item.isget == 1) {
              item.btnText = '已领取';
              item.color = '#999'
            } else if (item.isget == 0) {
              item.btnText = '点击领取';
            }
          })
          console.log(123)
          that.setData({
            [`tickets[${index}]`]: [...that.data.tickets[index], ...res.result.coupon_list],
            [`status[${index}].pagination`]: that.data.status[index].pagination + 1
          }, () => {
            setTimeout(() => {
              that.draw(that.data.tickets[that.data.currentData])
            }, 300)
            that.setData({
              hiddenLoading: true
            })
            console.log(234)
          })
        }
      } else {
        throw res.msg;
      }
    }).catch(err => {
      that.setData({
        hiddenLoading: true
      })
      app.showInfo(err.toString())
    })
  },

  // 点击领取优惠券
  getticket(e) {
    const that = this;
    let id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;
    let token = app.globalData.token;
    let tickets = that.data.tickets;
    //根据id领取优惠券
    let json = {
      token,
      coupon_id: id
    }
    let jsonData = app.utils.getSignData(json);
    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.coupon, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        wx.showToast({
          title: res.msg,
          icon: 'success',
          duration: 2000
        })
        tickets[that.data.currentData][index].isget = 1;
        tickets[that.data.currentData][index].btnText = "已领取";
        tickets[that.data.currentData][index].color = "#999";
        tickets[that.data.currentData][index].send_num = parseInt(tickets[that.data.currentData][index].send_num) + 1
        that.setData({
          tickets
        }, ()=>{
          that.draw(that.data.tickets[that.data.currentData]);
        })

      } else {
        throw res.msg;
      }
    }).catch(err => {
      that.setData({
        hiddenLoading: true
      })
      app.showInfo(err.toString())
    })
  },

  // 切换
  checkCurrent(e) {
    const that = this;
    that.setData({
      currentData: e.currentTarget.dataset.current
    }, () => {
      that.getData(parseInt(that.data.currentData) + 1);
      })
    that.setData({
      status: [
        {
          pagination: 1,
          isEnd: false,
          isEmpty: false
        },
        {
          pagination: 1,
          isEnd: false,
          isEmpty: false
        },
        {
          pagination: 1,
          isEnd: false,
          isEmpty: false
        }
      ]
    })
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    console.log(options.share_img, 1111111111)
    if(options.store_id){
      that.setData({
        selectstoreid: options.store_id,
      });
      wx.setStorageSync('shadowstoreid', options.store_id);
    }
  
    that.setData({
      shareImg :  options.share_img,
    });
    let systemInfo = wx.getSystemInfoSync()
    that.setData({
      windowWidth: systemInfo.windowWidth,
      scrollHeight: systemInfo.windowHeight - 110 / 750 * systemInfo.windowWidth,
      pos_type: options.type
    });
    that.getData(1);
  },

  onShow:function(){
    const that = this;
    //数据统计
    if (that.data.pos_type) {
      app.statistics("page/detail/pages/tickets/tickets", "领券中心", that.data.pos_type)
    } else {
      app.statistics("page/detail/pages/tickets/tickets", "领券中心")
    }
  },
  onReachBottom() {
    const that = this;
    that.getMoreData();
  },
    /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    const that = this;
    var storeid =  that.data.selectstoreid ? that.data.selectstoreid : app.globalData.address.select_store_id;
    return {
      title: '领券中心',
      path: `page/detail/pages/tickets/tickets?store_id=${storeid}`, // 分享后打开的页面
      imageUrl: that.data.shareImg ? that.data.domain + that.data.shareImg : ''
    }
  },
})